<template>
  <div class="booking-container">
    <div class="form-header">
      <div class="car-animation">
        <div class="car">
          <div class="car-body"></div>
          <div class="wheel wheel-left"></div>
          <div class="wheel wheel-right"></div>
        </div>
      </div>
      <h1>豪华汽车预约</h1>
      <p class="subtitle">遇见心仪的座驾，开启尊享之旅</p>
    </div>

    <form @submit.prevent="handleSubmit" class="booking-form">
      <div class="form-group">
        <label>
          <i class="icon">👤</i>
          <input 
            v-model="formData.name"
            type="text"
            placeholder="您的姓名"
            required
          >
        </label>
      </div>

      <div class="form-group">
        <label>
          <i class="icon">📱</i>
          <input 
            v-model="formData.phone"
            type="tel"
            placeholder="手机号码"
            pattern="[0-9]{11}"
            required
          >
        </label>
      </div>

      <div class="form-group verification-group">
        <label>
          <i class="icon">🔑</i>
          <input 
            v-model="formData.code"
            type="text"
            placeholder="验证码"
            required
          >
        </label>
        <button type="button" class="send-code-btn" @click="sendCode" :disabled="isSendingCode || countdown > 0">
          {{ countdown > 0 ? `${countdown}秒后重试` : (isSendingCode ? '发送中...' : '获取验证码') }}
        </button>
      </div>

      <div class="form-section">
        <h3 class="section-title">选择车型</h3>
        <div class="form-group car-select">
          <select v-model="formData.brand" required @change="handleBrandChange">
            <option value="" disabled selected>选择品牌</option>
            <option v-for="brand in carBrands" :key="brand.id" :value="brand">
              {{ brand.name }}
            </option>
          </select>

          <select v-model="formData.model" required :disabled="!formData.brand">
            <option value="" disabled selected>选择车型</option>
            <option v-for="model in selectedBrandModels" :key="model.id" :value="model">
              {{ model.name }}
            </option>
          </select>
        </div>
      </div>

      <div class="form-section">
        <h3 class="section-title">选择地区</h3>
        <div class="form-group city-select">
          <select v-model="formData.province" required @change="handleProvinceChange">
            <option value="" disabled selected>选择省份</option>
            <option v-for="province in cities" :key="province.id" :value="province">
              {{ province.name }}
            </option>
          </select>

          <select 
            v-model="formData.city" 
            required 
            :disabled="!formData.province"
            @change="handleCityChange"
          >
            <option value="" disabled selected>选择城市</option>
            <option v-for="city in selectedProvinceCities" :key="city.id" :value="city">
              {{ city.name }}
            </option>
          </select>

          <select 
            v-model="formData.district" 
            required 
            :disabled="!formData.city"
          >
            <option value="" disabled selected>选择区域</option>
            <option v-for="district in selectedCityDistricts" :key="district.id" :value="district">
              {{ district.name }}
            </option>
          </select>
        </div>
      </div>

      <div class="form-group">
        <label>
          <input 
          class="checkbox"
            type="checkbox"
            v-model="formData.agreePrivacyPolicy"
            required
          >
          <span class="privacyPolicyText">我已阅读并同意</span>
          <span @click="toPrivacyPolicy" class="privacyPolicyText">隐私协议</span>
        </label>
      </div>

      <button type="submit" class="submit-btn">
        立即预约
        <span class="btn-effect"></span>
      </button>
    </form>
  </div>
</template>

<script>
export default {
  name: 'CarBookingForm',
  data() {
    return {
      formData: {
        name: '',
        phone: '',
        code: '',
        brand: '',
        model: '',
        province: '',
        city: '',
        district: '',
        agreePrivacyPolicy: true
      },
      carBrands: [],
      cities: [],
      isSendingCode: false,
      countdown: 0, // 倒计时初始值
      countdownInterval: null // 用于存储计时器
    }
  },
  computed: {
    selectedBrandModels() {
      return this.formData.brand ? this.formData.brand.children || [] : []
    },
    selectedProvinceCities() {
      return this.formData.province ? this.formData.province.children || [] : []
    },
    selectedCityDistricts() {
      return this.formData.city ? this.formData.city.children || [] : []
    }
  },
  methods: {
    async fetchCarModels() {
      try {
        const response = await fetch('http://49.232.138.63:8000/webapi/carModel/getAll')
        const result = await response.json()
        this.carBrands = result.data
      } catch (error) {
        console.error('获取车型数据失败:', error)
      }
    },
    async fetchCities() {
      try {
        const response = await fetch('http://49.232.138.63:8000/webapi/city/getAll')
        const result = await response.json()
        this.cities = result.data
      } catch (error) {
        console.error('获取城市数据失败:', error)
      }
    },
    handleBrandChange() {
      this.formData.model = ''
    },
    handleProvinceChange() {
      this.formData.city = ''
      this.formData.district = ''
    },
    handleCityChange() {
      this.formData.district = ''
    },
    async sendCode() {
      if (!this.formData.phone) {
        alert('请先输入手机号码')
        return
      }

      this.isSendingCode = true
      try {
        const response = await fetch('http://49.232.138.63:8000/webapi/sendCode', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({ phone: this.formData.phone })
        })

        const result = await response.json()

        if (result.code === 0) {
          alert('验证码已发送，请查收短信')
          this.startCountdown() // 开始倒计时
        } else {
          alert(result.message || '发送验证码失败，请稍后重试')
        }
      } catch (error) {
        console.error('发送验证码失败:', error)
        alert('发送验证码失败，请稍后重试')
      } finally {
        this.isSendingCode = false
      }
    },
    startCountdown() {
      this.countdown = 60
      this.countdownInterval = setInterval(() => {
        if (this.countdown > 0) {
          this.countdown--
        } else {
          clearInterval(this.countdownInterval)
        }
      }, 1000)
    },
    async handleSubmit() {
      if (!this.formData.agreePrivacyPolicy) {
        alert('请先阅读并同意隐私协议');
        return;
      }
      try {
        const submitData = {
          name: this.formData.name,
          phone: this.formData.phone,
          code: this.formData.code,
          carModelId: this.formData.model?.id,
          cityId: this.formData.district?.id
        }

        const response = await fetch('http://49.232.138.63:8000/webapi/enroll/save', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(submitData)
        })

        const result = await response.json()

        if (result.code === 0) {
          alert('预约成功！我们会尽快与您联系。')
          // 重置表单
          this.formData = {
            name: '',
            phone: '',
            code: '',
            brand: '',
            model: '',
            province: '',
            city: '',
            district: '',
            agreePrivacyPolicy: false
          }
        } else {
          alert(result.message || '预约失败，请稍后重试')
        }
      } catch (error) {
        console.error('提交失败:', error)
        alert('提交失败，请稍后重试')
      }
    },

    toPrivacyPolicy() {
      this.$router.push({
        name: 'PrivacyPolicy'
      })
    }
  },
  created() {
    this.fetchCarModels()
    this.fetchCities()
  }
}
</script>

<style scoped>
.booking-container {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
  background: linear-gradient(135deg, #1a1a1a 0%, #4a4a4a 100%);
}

.form-header {
  text-align: center;
  margin-bottom: 40px;
  padding: 20px;
  background: rgba(0, 0, 0, 0.2);
  border-radius: 20px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.car-animation {
  height: 100px;
  position: relative;
  overflow: hidden;
  margin: 20px 0;
}

.car {
  position: absolute;
  left: -100px;
  top: 50%;
  transform: translateY(-50%);
  animation: moveCar 3s infinite linear;
}

.car-body {
  width: 60px;
  height: 25px;
  background: linear-gradient(45deg, #FFD700, #FFA500);
  border-radius: 10px;
  position: relative;
}

.car-body::before {
  content: '';
  position: absolute;
  top: -15px;
  left: 10px;
  width: 35px;
  height: 15px;
  background: linear-gradient(45deg, #FFD700, #FFA500);
  border-radius: 5px 5px 0 0;
}

.wheel {
  width: 15px;
  height: 15px;
  background: #333;
  border-radius: 50%;
  position: absolute;
  bottom: -7px;
  animation: wheelRotate 1s infinite linear;
}

.wheel-left {
  left: 10px;
}

.wheel-right {
  right: 10px;
}

@keyframes moveCar {
  from { left: -100px; }
  to { left: calc(100% + 100px); }
}

@keyframes wheelRotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

h1 {
  font-size: 2.8em;
  margin-bottom: 15px;
  background: linear-gradient(45deg, #FFD700, #FFA500);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.1);
}

.subtitle {
  font-size: 1.2em;
  color: rgba(255, 255, 255, 0.8);
  margin-top: 10px;
}

.booking-form {
  display: flex;
  flex-direction: column;
  background: rgba(255, 255, 255, 0.1);
  padding: 40px;
  border-radius: 20px;
  backdrop-filter: blur(10px);
  box-shadow: 0 8px 32px rgba(31, 38, 135, 0.15);
  border: 1px solid rgba(255, 255, 255, 0.18);
}

.form-section {
  margin-bottom: 30px;
  padding: 20px;
  background: rgba(0, 0, 0, 0.2);
  border-radius: 15px;
}

.section-title {
  font-size: 1.2em;
  color: #FFD700;
  margin-bottom: 15px;
  padding-left: 10px;
  border-left: 3px solid #FFD700;
}

.form-group {
  display: flex;
  margin-bottom: 25px;
  position: relative;
}

.verification-group {
  display: flex;
  align-items: center;
}

.icon {
  position: absolute;
  left: 15px;
  top: 50%;
  transform: translateY(-50%);
  font-style: normal;
  z-index: 1;
}

label {
  display: flex;
  align-items: center;
  position: relative;
  flex: 1;
}

input {
  width: 100%;
  padding: 15px 15px 15px 45px;
  border: none;
  border-radius: 12px;
  background: rgba(255, 255, 255, 0.1);
  color: white;
  font-size: 16px;
  transition: all 0.3s ease;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

input:focus {
  outline: none;
  background: rgba(255, 255, 255, 0.15);
  border-color: #FFD700;
  box-shadow: 0 0 15px rgba(255, 215, 0, 0.2);
}

input::placeholder {
  color: rgba(255, 255, 255, 0.6);
}

select {
  width: 100%;
  padding: 15px;
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 12px;
  background: rgba(255, 255, 255, 0.9);
  color: #333;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
}

select:focus {
  outline: none;
  border-color: #FFD700;
  box-shadow: 0 0 15px rgba(255, 215, 0, 0.2);
}

select option {
  background: white;
  color: #333;
  padding: 10px;
}

select:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  background: rgba(255, 255, 255, 0.5);
}

select:hover:not(:disabled) {
  background: rgba(255, 255, 255, 1);
  transform: translateY(-2px);
}

.car-select, .city-select {
  display: grid;
  gap: 15px;
}

.car-select {
  grid-template-columns: repeat(2, 1fr);
}

.city-select {
  grid-template-columns: repeat(3, 1fr);
}

.submit-btn {
  width: 100%;
  padding: 18px;
  border: none;
  border-radius: 12px;
  background: linear-gradient(45deg, #FFD700, #FFA500);
  color: #000;
  font-size: 18px;
  font-weight: bold;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: all 0.3s ease;
  text-transform: uppercase;
  letter-spacing: 1px;
  box-shadow: 0 4px 15px rgba(255, 215, 0, 0.2);
}

.submit-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(255, 215, 0, 0.3);
}

.btn-effect {
  position: absolute;
  top: -50%;
  left: -50%;
  width: 200%;
  height: 200%;
  background: rgba(255, 255, 255, 0.2);
  transform: rotate(45deg);
  animation: btnEffect 2s infinite linear;
}

@keyframes btnEffect {
  from { transform: rotate(45deg) translate(-50%, -50%); }
  to { transform: rotate(45deg) translate(50%, 50%); }
}

@media (max-width: 480px) {
  .booking-container {
    padding: 10px;
  }
  
  .booking-form {
    padding: 20px;
  }
  
  .car-select, .city-select {
    grid-template-columns: 1fr;
  }
  
  h1 {
    font-size: 2.2em;
  }
}

.send-code-btn {
  margin-left: 10px;
  padding: 10px 15px;
  background-color: #FFD700;
  border: none;
  border-radius: 5px;
  color: #333;
  cursor: pointer;
  transition: background-color 0.3s;
}

.send-code-btn:hover {
  background-color: #FFA500;
}

.send-code-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.checkbox {
  width: 15px;
  height: 15px;
  margin-right: 5px;
}

.privacyPolicyText {
  color: #fff;
  cursor: pointer;
}

</style>